package com.example.a17376046_xsh_finaltest.Activity;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import android.Manifest;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.a17376046_xsh_finaltest.R;
import com.example.a17376046_xsh_finaltest.dao.MyDatabaseHelper;
import com.example.a17376046_xsh_finaltest.dao.MytabOperate;
import com.example.a17376046_xsh_finaltest.utils.Autjcode;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends Activity implements OnClickListener,
		OnFocusChangeListener {
	private Button registerBack;
	private Button registerCheck;
	private Button registerBtn;
	private EditText registrationUserName;
	private EditText registrationPassWord;
	private EditText registerAuth;
	private EditText turePassword;
	private TextView registerBackText;
	private TextView registerIdText;
	private TextView registerPwText;
	private TextView turePwText;
	private TextView registerAuthText;
	private ImageView registerAuthimg;
	private String isPhone, isPassword, isTruePassword, Autecode, Autecodeimg;
	private int flagPhone, flagPassword, flagTruePassword, flagAutecode;
	private SQLiteOpenHelper helper;
	private MytabOperate mylogin;
	Response response;
	Button registration;
	public static int REGISTRATION_USER = 2;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 0:
					Toast.makeText(RegisterActivity.this, "注册失败，当前用户名已经注册", Toast.LENGTH_SHORT).show();
					break;
				case 1:
					//有些手机不显示通知
					NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
					Notification notification = new NotificationCompat.Builder(RegisterActivity.this, "first")
							.setContentTitle("注册成功")
							.setContentText("用户 " + registrationUserName.getText().toString() + "  注册成功")
							.setWhen(System.currentTimeMillis())
							.setAutoCancel(true)
							.build();
					manager.notify(1, notification);
					Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
					Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
					startActivity(intent);
					break;
				case 2:
					Toast.makeText(RegisterActivity.this, "当前无网络", Toast.LENGTH_SHORT).show();
					break;
				default:
					break;
			}
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_register);
		helper = new MyDatabaseHelper(this);
		initView();
	}

	private void initView() {
		registerBack =findViewById(R.id.registerBack);
		registerBack.setOnClickListener(this);
		registerCheck =findViewById(R.id.registerCheck);
		registerCheck.setOnClickListener(this);
		registerBtn =findViewById(R.id.registerBtn);
		registerBtn.setOnClickListener(this);
		registerBackText =findViewById(R.id.registerBackText);
		registerBackText.setOnClickListener(this);

		registrationUserName =findViewById(R.id.registerId);
		registrationUserName.setOnFocusChangeListener(this);
		registrationPassWord =findViewById(R.id.registerPassword);
		registrationPassWord.setOnFocusChangeListener(this);
		registerAuth =findViewById(R.id.registerAuth);
		registerAuth.setOnFocusChangeListener(this);
		registerAuth.setOnClickListener(this);
		turePassword = findViewById(R.id.turePassword);
		turePassword.setOnFocusChangeListener(this);

		registerAuthimg =findViewById(R.id.registerAuthimg);
		registerAuthimg.setImageBitmap(Autjcode.getInstance().createBitmap());

		registerIdText = findViewById(R.id.registerIdText);
		registerPwText = findViewById(R.id.registerPwText);
		turePwText = findViewById(R.id.turePwText);
		registerAuthText = findViewById(R.id.registerAuthText);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.registerBack:
			RegisterActivity.this.finish();
			break;
		case R.id.registerBackText:
			RegisterActivity.this.finish();
			break;
		case R.id.registerAuth:
			registerAuth.setFocusable(true);
			registerAuth.setFocusableInTouchMode(true);
			registerAuth.requestFocus();
			registerAuth.findFocus();
			break;
		case R.id.registerCheck:
			registerAuthimg.setImageBitmap(Autjcode.getInstance()
					.createBitmap());
			break;
		case R.id.registerBtn:
			if (ContextCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
				ActivityCompat.requestPermissions(RegisterActivity.this, new String[]{Manifest.permission.INTERNET}, 1);
			} else {
				register();
			}
			/*registerAuth.setFocusable(false);
			isPhone = registrationUserName.getText().toString();
			if (flagAutecode == 1 && flagPassword == 1 && flagPhone == 1
					&& flagTruePassword == 1) {
				if (new MyloginCursor(
						RegisterActivity.this.helper.getReadableDatabase())
						.find(isPhone).size() == 0) {
					mylogin = new MytabOperate(helper.getWritableDatabase());
					mylogin.insert(isPhone, isPassword);
					new AlertDialog.Builder(RegisterActivity.this)
							.setTitle("提示")
							.setMessage("注册成功！")
							.setPositiveButton("确认",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											Intent i = new Intent(
													RegisterActivity.this,
													LoginActivity.class);
											i.putExtra("myId", isPhone);
											RegisterActivity.this.finish();
											startActivity(i);
										}
									}).show();

				} else {
					new AlertDialog.Builder(RegisterActivity.this)
							.setTitle("提示").setMessage("用户已存在")
							.setPositiveButton("确认", null).show();
				}
			} else {
				Toast.makeText(RegisterActivity.this, "注册失败",
						Toast.LENGTH_SHORT).show();
			}*/
			break;
		default:
			break;
		}

	}

	public void register() {
		if ((registrationUserName.getText().toString().length() == 0 || registrationUserName.getText().toString() == null)
				|| registrationPassWord.getText().toString().length() < 6
				|| !registrationUserName.getText().toString().equals(stringFilter(registrationUserName.getText().toString()))) {
			Toast.makeText(RegisterActivity.this, "不能输入非法字符！！！", Toast.LENGTH_SHORT).show();
		} else {
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						OkHttpClient client = new OkHttpClient();
						RequestBody requestBody = new FormBody.Builder()
								.add("userName", registrationUserName.getText().toString())
								.add("passWord", registrationPassWord.getText().toString())
								.build();
						Request request = new Request.Builder()
								.url("http://106.13.133.171/17376016_gy_StudyGo/registration")
								.post(requestBody)
								.build();
						response = client.newCall(request).execute();
						if (response.body().string().equals("1")) {
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
						} else {
							Message message = new Message();
							message.what = 0;
							handler.sendMessage(message);
						}

						//Log.d("MainActivity", "没有错误" + registrationUserName.getText());
					} catch (IOException e) {
						e.printStackTrace();
						Log.d("123",e.toString());
						/*Message message = new Message();
						message.what = REGISTRATION_USER;
						handler.sendMessage(message);*/
					}
				}
			}).start();
		}
	}
	public static String stringFilter(String str) throws PatternSyntaxException {
		String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";
		Pattern pattern = Pattern.compile(regEx);
		Matcher m = pattern.matcher(str);
		return m.replaceAll("").trim();
	}
	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		switch (requestCode) {
			case 1:
				if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
					register();
				} else {
					Toast.makeText(RegisterActivity.this, "你没有允许权限的运行", 0).show();
				}
				break;
			default:
		}
	}
	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		isPhone = registrationUserName.getText().toString();
		isPassword = registrationPassWord.getText().toString();
		isTruePassword = turePassword.getText().toString();
		Autecode = registerAuth.getText().toString();
		Autecodeimg = Autjcode.getInstance().getCode().toUpperCase();
		switch (v.getId()) {
		case R.id.registerId:
			if (hasFocus == false) {
				Pattern pattern = Pattern.compile("^1[3,5,8]\\d{9}$");
				Matcher matcher = pattern.matcher(isPhone);
				if (matcher.find()) {
					registerIdText.setVisibility(View.INVISIBLE);
					flagPhone = 1;
				} else {
					if (registrationUserName.length() != 0) {
						registerIdText.setVisibility(View.VISIBLE);
					}
				}
			}
			break;
		case R.id.registerPassword:
			if (hasFocus == false) {
				if ((isPassword.length() < 6 || isPassword.length() > 20)
						&& isPassword.length() != 0) {
					registerPwText.setVisibility(View.VISIBLE);
				} else {
					registerPwText.setVisibility(View.INVISIBLE);
					flagPassword = 1;
				}
			}
			break;
		case R.id.turePassword:
			if (hasFocus == false) {
				if (isTruePassword.equals(isPassword)) {
					turePwText.setVisibility(View.INVISIBLE);
					flagTruePassword = 1;
				} else {
					if (turePassword.length() != 0) {
						turePwText.setVisibility(View.VISIBLE);
					}
				}
			}
			break;
		case R.id.registerAuth:
			if (hasFocus == false) {
				if (Autecode.toUpperCase().equals(Autecodeimg)) {
					registerAuthText.setVisibility(View.INVISIBLE);
					flagAutecode = 1;
				} else {
					if (registerAuth.length() != 0) {
						registerAuthText.setVisibility(View.VISIBLE);
					}
				}
			}
			break;
		default:
			break;
		}
	}
}
